package com.wa.mapper.config;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @author WangPengfei
 * @date 2018/5/25
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
@Component
public class MybatisSelectPlugin implements Interceptor {
    private Logger logger = LoggerFactory.getLogger(MybatisSelectPlugin.class);
    private final static String FIELD_IS_DELETE = "isDelete";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
            if (!ms.getId().contains("com.wa")) {
                return invocation.proceed();
            }

            Object parameter = invocation.getArgs()[1];
            if (parameter instanceof BaseEntity) {
                Class classParameter = parameter.getClass();

                Field field = classParameter.getSuperclass().getDeclaredField(FIELD_IS_DELETE);
                field.setAccessible(true);
                Object value = field.get(parameter);
                if (value != null) {
                    return invocation.proceed();
                }
            } else {
                return invocation.proceed();
            }
            BoundSql boundSql = ms.getBoundSql(parameter);
            String sql = boundSql.getSql();
            if (!sql.contains("where") && !sql.contains("WHERE")) {
                sql += " where ";
            } else {
                sql += " and ";
            }
            sql += " ( is_delete is null or is_delete=0 )";
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), parameter);
            Executor executor = (Executor) invocation.getTarget();
            return executor.query(ms, parameter, RowBounds.DEFAULT, (ResultHandler) invocation.getArgs()[3], CacheKey.NULL_CACHE_KEY, newBoundSql);
        } catch (Exception e) {
            logger.error("通用设置值时出错" + e.getMessage(), e);
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
